package exam;

import java.util.Scanner;
import java.util.concurrent.CountDownLatch;

public class T10 {
    private static char[] chars;
    private static int repeatNum; // repeat num
    private static final int THREAD_NUM = 4; // thread num
    private static final char[] TEMPLATE = {'A', 'B', 'C', 'D'};
    private static int index = 0; // index of chars
    private static volatile int state = 0;

    public static void main(String[] args) throws InterruptedException {
        Scanner scanner = new Scanner(System.in);
        System.out.print("please input: ");
        repeatNum = scanner.nextInt();
        if(repeatNum <= 0)
            throw new IllegalArgumentException("must be more then zero");
        chars = new char[repeatNum * THREAD_NUM];

        CountDownLatch latch = new CountDownLatch(THREAD_NUM);
        for (int i = 0; i < THREAD_NUM; i++) {
            final int ii = i;
            new Thread(() -> {
                for (int j = 0; j < repeatNum; j++) {
                    for(;;) {
                        if (ii == state) {
                            chars[index++] = TEMPLATE[ii];
                            if (state + 1 >= THREAD_NUM)
                                state = 0;
                            else
                                state ++;
                            break;
                        }
                    }
                }
                latch.countDown();
            }).start();
        }
        latch.await();
        System.out.println(new String(chars));
    }
}
